package com.monkeygroup.mygoplus.ecchat.ui.contact;

import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.monkeygroup.mygoplus.MyGoApplication;
import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.base.BaseActivity;
import com.monkeygroup.mygoplus.common.utils.PinyinUtils;
import com.monkeygroup.mygoplus.common.utils.VilidateUtil;
import com.monkeygroup.mygoplus.ecchat.ui.chatting.ChattingActivity;
import com.monkeygroup.mygoplus.ecchat.ui.chatting.ChattingFragment;
import com.monkeygroup.mygoplus.ecchat.ui.contact.adapter.MemberListAdapter;
import com.monkeygroup.mygoplus.ecchat.ui.contact.adapter.SearchRecordAdapter;
import com.monkeygroup.mygoplus.ecchat.ui.contact.db.ContactRecord;
import com.monkeygroup.mygoplus.ecchat.ui.contact.entity.ContactMemberDTO;
import com.monkeygroup.mygoplus.http.HttpModel;
import com.monkeygroup.mygoplus.http.RequestUrl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/6/26.
 */
public class SearchFriendsActivity extends BaseActivity implements View.OnClickListener {
    private LinearLayout search_history_layout;
    private ListView history_list_view, contentListView;
    private EditText search_edit_text;
    private ImageView searchClearButton;
    private TextView search_record_tip, more_contact_history, clear_contact_history;
    private ArrayList<ContactMemberDTO> friendsList = new ArrayList<>();
    private ArrayList<ContactMemberDTO> contentList = new ArrayList<>();
    private List<Map<String, Object>> recordList = new ArrayList<>();
    private SearchRecordAdapter recordAdapter;
    private MemberListAdapter adapter;
    private static int pageNo = 0;
    private final int pageSize = 20;
    private Filter myFilter;
    private final String TAG = "SearchFriendsActivity";

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_friends_search);
    }

    @Override
    public void initView() {
        contentListView = (ListView) findViewById(R.id.contentListView);
        contentListView.setVisibility(View.GONE);
        search_edit_text = (EditText) findViewById(R.id.search_edit_text);
        search_edit_text.addTextChangedListener(new OnTextWatcherListener());
        search_edit_text.setHint("搜索聯繫人");
        searchClearButton = (ImageView) findViewById(R.id.search_edittext_clear_btn);
        searchClearButton.setVisibility(View.GONE);
        search_history_layout = (LinearLayout) findViewById(R.id.search_history_layout);
        search_history_layout.setVisibility(View.VISIBLE);
        search_record_tip = (TextView) findViewById(R.id.search_record_tip);
        history_list_view = (ListView) findViewById(R.id.history_list_view);
        more_contact_history = (TextView) findViewById(R.id.more_contact_history);
        clear_contact_history = (TextView) findViewById(R.id.clear_contact_history);
        clear_contact_history.setVisibility(View.VISIBLE);
    }

    @Override
    public void setListener() {
        findViewById(R.id.layout_back).setOnClickListener(this);
        clear_contact_history.setOnClickListener(this);
        more_contact_history.setOnClickListener(this);
        searchClearButton.setOnClickListener(this);

        contentListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (id == -1)
                    return;

                ContactMemberDTO data = adapter.getItem(position);
                addHistoryToDatabase(data.getName());

                Intent intent = new Intent(SearchFriendsActivity.this, ChattingActivity.class);
                intent.putExtra(ChattingFragment.RECIPIENTS, data.getId());
                startActivity(intent);
            }
        });

        history_list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (id == -1)
                    return;

                String content = (String) recordAdapter.getItem(position).get("content");
                search_edit_text.setText(content);
                addHistoryToDatabase(content);
            }
        });
    }

    @Override
    public void doEvent() {
        initAdapter();

        if (MyGoApplication.getContacts() != null && MyGoApplication.getContacts().size() > 0) {
            friendsList.clear();
            friendsList.addAll(MyGoApplication.getContacts().values());
        } else {
            doAllContact();
        }

        initData();
    }

    private void initData() {
        pageNo = 0;
        refreshHistory();
    }

    private void refreshHistory() {
        ContactRecord model = new ContactRecord(this);
        List<Map<String, Object>> list = model.getRecords(pageNo, pageSize);

        if (pageNo == 0) {
            recordList.clear();
        }

        if (list == null || list.size() == 0) {
            more_contact_history.setVisibility(View.GONE);
            if (pageNo == 0) {
                clear_contact_history.setVisibility(View.GONE);
            }
        } else {
            recordList.addAll(list);
            if (list.size() < pageSize) {
                more_contact_history.setVisibility(View.GONE);
            }
        }

        if (recordList.size() > 0) {
            history_list_view.setVisibility(View.VISIBLE);
            search_record_tip.setVisibility(View.GONE);

            recordAdapter = new SearchRecordAdapter(this, recordList);
            history_list_view.setAdapter(recordAdapter);
        } else {
            search_record_tip.setVisibility(View.VISIBLE);
            history_list_view.setVisibility(View.GONE);
        }
    }

    private void addHistoryToDatabase(String keyword) {
        Map<String, Object> map = new HashMap<>();
        map.put(ContactRecord.COLUMN_CONTENT, keyword);
        map.put(ContactRecord.COLUMN_LATEST_TIME, String.valueOf(System.currentTimeMillis()));
        map.put(ContactRecord.COLUMN_TOTAL_COUNT, 1);

        ContactRecord model = new ContactRecord(this);
        model.addRecord(map);
    }

    private void initAdapter() {
        adapter = new MemberListAdapter(SearchFriendsActivity.this, contentList);
        contentListView.setAdapter(adapter);
    }

    private void setFriendsData(List<Map<String, String>> list) {
        List<ContactMemberDTO> friendList = new ArrayList<>();
        for (Map<String, String> item : list) {
            ContactMemberDTO memberDTO = new ContactMemberDTO();
            if (item.get("username") != null && !item.get("username").equals("")) {
                memberDTO.setName((String) item.get("username"));
            } else if (item.get("userID") != null && !item.get("userID").equals("")) {
                memberDTO.setName((String) item.get("userID"));
            } else {
                memberDTO.setName((String) item.get("mobile"));
            }

            memberDTO.setId((String) item.get("mobile"));
            memberDTO.setHeadUrl((String) item.get("headIcon"));
            memberDTO.setStatus(item.get("status"));
            memberDTO.setEmail(item.get("email"));
            memberDTO.setIsOffice(item.get("isOffice"));
            memberDTO.setNotification(item.get("notification"));
            memberDTO.setRemark(item.get("remark"));
            friendList.add(memberDTO);
        }

        friendsList.clear();
        friendsList.addAll(friendList);

        Map<String, ContactMemberDTO> friends = new HashMap<>();
        for (ContactMemberDTO memberDTO : friendList) {
            friends.put(memberDTO.getId(), memberDTO);
        }
        MyGoApplication.setContacts(friends);
    }

    private void doAllContact() {
        if (MyGoApplication.myECUserid.equals(""))
            return;

        String requestUrl = RequestUrl.baseUrl + RequestUrl.requestAllContact;
        HttpModel httpModel = new HttpModel(requestUrl, getParams(), new HttpModel.SimpleOnHttpRequestListener() {
            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {
                if (VilidateUtil.isSuccess(resultCode)) {
                    Map<String, Object> map = (Map) data;
                    List<Map<String, String>> list = (ArrayList) map.get("friends");
                    setFriendsData(list);

                } else {
                    Toast.makeText(SearchFriendsActivity.this, resultMsg, Toast.LENGTH_SHORT).show();
                }
            }
        }, true);

        httpModel.startRequest();
    }

    private Map<String, String> getParams() {
        Map<String, String> params = new HashMap<>();
        params.put("mobile", MyGoApplication.myECUserid);

        return params;
    }

    class OnTextWatcherListener implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            Log.d(TAG, "beforeTextChanged");
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Log.d(TAG, "onTextChanged");
        }

        @Override
        public void afterTextChanged(Editable s) {
            Log.d(TAG, "afterTextChanged");
            String keyword = search_edit_text.getText().toString();
            if (keyword != null && !keyword.equals("")) {
                searchClearButton.setVisibility(View.VISIBLE);

                getFilter().filter(keyword);
            } else {
                searchClearButton.setVisibility(View.GONE);
                contentListView.setVisibility(View.GONE);
                search_history_layout.setVisibility(View.VISIBLE);
            }

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_back:
                finish();
                break;
            case R.id.search_edittext_clear_btn:
                search_edit_text.setText("");
                searchClearButton.setVisibility(View.GONE);
                break;
            case R.id.clear_contact_history:
                ContactRecord model = new ContactRecord(this);
                model.deleteAllRecords();

                pageNo = 0;
                refreshHistory();
                break;
            case R.id.more_contact_history:
                pageNo++;
                refreshHistory();
                break;
            default:
                break;
        }
    }

    public Filter getFilter() {
        if (myFilter == null) {
            myFilter = new MyFilter(friendsList);
        }
        return myFilter;
    }

    private class MyFilter extends Filter {
        List<ContactMemberDTO> mOriginalList = null;

        public MyFilter(List<ContactMemberDTO> myList) {
            this.mOriginalList = myList;
        }

        @Override
        protected synchronized FilterResults performFiltering(
                CharSequence prefix) {
            FilterResults results = new FilterResults();
            if (mOriginalList == null) {
                results.values = null;
                results.count = 0;
                return results;
            }

            if (prefix == null || prefix.length() == 0) {
                results.values = null;
                results.count = 0;
            } else {
                String prefixString = prefix.toString();
                prefixString = prefixString.toLowerCase();
                int count = mOriginalList.size();
                List<ContactMemberDTO> newValues = new ArrayList<>();
                for (int i = 0; i < count; i++) {
                    final ContactMemberDTO user = mOriginalList.get(i);
                    String name = user.getName();
                    if (name == null)
                        continue;

                    String userNum = PinyinUtils.getPingYin(user.getName());
                    userNum = userNum.toLowerCase();
                    if (name.contains(prefixString)
                            || userNum.contains(prefixString)) {
                        newValues.add(user);
                    }
                }
                results.values = newValues;
                results.count = newValues.size();
            }

            return results;
        }

        @Override
        protected synchronized void publishResults(CharSequence constraint,
                                                   FilterResults results) {
            if (results.count > 0) {
                contentListView.setVisibility(View.VISIBLE);
                search_history_layout.setVisibility(View.GONE);

                contentList.clear();
                contentList.addAll((List<ContactMemberDTO>) results.values);
                adapter.notifyDataSetChanged();

            } else {
                contentListView.setVisibility(View.GONE);
                search_history_layout.setVisibility(View.VISIBLE);
                Toast.makeText(SearchFriendsActivity.this, "没有搜索结果", Toast.LENGTH_SHORT).show();
            }
        }
    }

}
